package com.sky.sky_common.util;

import java.io.ByteArrayInputStream;

import org.springframework.stereotype.Component;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.sky.sky_common.config.AliyunOssProperties;

@Component
public class AliossService {
    private final AliyunOssProperties aliyunOssProperties;

    public AliossService(AliyunOssProperties aliyunOssProperties) {
        this.aliyunOssProperties = aliyunOssProperties;
    }

    /**
     * 上传文件并获取url地址
     * @param fileName 文件名称
     * @param file 文件字节数组
     * @return 文件的url地址，异常返回空字符串:""
     */
    public String uploadFileAndGetUrl(String fileName, byte[] file) {
        // 创建OSSClient实例
        OSS ossClient = getOSSClient();
        try{
            // 上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                aliyunOssProperties.getBucketName(),
                fileName,
                new ByteArrayInputStream(file)
            );
            // https://a1185640949.oss-cn-qingdao.aliyuncs.com/exampledir.png
            // https://bucketName.Endpoint/fileName
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            if(result == null)
                throw new Exception("上传文件失败");
            // 拼接字符串，前提是公开的bucket
            StringBuilder sb = new StringBuilder();
            sb.append("https://")
                .append(aliyunOssProperties.getBucketName())
                .append(".")
                .append(aliyunOssProperties.getEndpoint().replace("https://", ""))
                .append("/")
                .append(fileName);
            return sb.toString();
        }catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        }catch(Exception e){
            System.out.println(e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "";
    }

    // todo 根据图片的url地址解析出云端图片地址，并删除
    public void deleteSingleByUrl(String url){
        
    }

    private OSS getOSSClient(){
        // 构建客户端
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        return OSSClientBuilder.create()
            .endpoint(aliyunOssProperties.getEndpoint())
            .credentialsProvider(
                new DefaultCredentialProvider(
                    aliyunOssProperties.getAccessKeyId(),
                    aliyunOssProperties.getAccessKeySecret()
                )
            )
            .clientConfiguration(clientBuilderConfiguration)
            .region("cn-qingdao")
            .build();
    }




}
